package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by csuarez on 17/01/14.
 */
public class Library {
    private List<Borrowable> borrowables;

    public Library(List<Borrowable> borrowables) {
        this.borrowables = borrowables;
    }

    public boolean checkOut(String title, User user) {
        Borrowable borrowableToCheckOut = getBorrowable(title);

        if(borrowableToCheckOut == null || borrowableToCheckOut.canBeCheckedOut()== false) {
            return false;
        }

        checkInOrCheckOutBook(title, false);
        user.addToCheckedOut(getBorrowable(title));
        return true;
    }

    public boolean checkIn(String title, User user) {
        Borrowable borrowableToCheckIn = getBorrowable(title);

        if(borrowableToCheckIn == null || borrowableToCheckIn.canBeCheckedIn() == false){
            return false;
        }

        checkInOrCheckOutBook(title, true);
        user.removeFromCheckedOut(borrowableToCheckIn);
        return true;
    }

    public List<Borrowable> getAvailableBooks() {
        return getAvailableBorrowables(BorrowableType.BOOK);
    }

    public List<Borrowable> getAvailableMovies() {
        return getAvailableBorrowables(BorrowableType.MOVIE);
    }

    private void checkInOrCheckOutBook(String title, Boolean checkIn){
        Borrowable borrowable = getBorrowable(title);
        if(checkIn==true){
            borrowable.checkIn();
        }else{
            borrowable.checkOut();
        }
    }

    private Borrowable getBorrowable(String title){
        for(Borrowable borrowable: borrowables){
            if(borrowable.getTitle().equals(title)){
                return borrowable;
            }
        }
        return null;
    }

    private List<Borrowable> getAvailableBorrowables(BorrowableType borrowableType) {
        List<Borrowable> availableBorrowables = new ArrayList<Borrowable>();

        for(Borrowable borrowable : borrowables){
            if(borrowable.canBeCheckedOut() && borrowable.getType() == borrowableType){
                availableBorrowables.add(borrowable);
            }
        }
        return availableBorrowables;
    }
}
